package de.muahd.saga.ui.springmvc.config;

import java.util.List;
import java.util.Properties;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.BeanNameViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@ComponentScan(basePackages={"de.muahd.saga.ui.springmvc"})
@EnableWebMvc
public class MVCConfig extends WebMvcConfigurerAdapter {

	@Bean
	public BeanNameViewResolver beanNameViewResolver() {
		BeanNameViewResolver b = new BeanNameViewResolver();
		b.setOrder(1);
		return b;
	}

	@Bean
	public InternalResourceViewResolver internalResourceViewResolver() {
		InternalResourceViewResolver b = new InternalResourceViewResolver();
		b.setSuffix(".jsp");
		b.setPrefix("/WEB-INF/jsp/");
		b.setOrder(2);
		return b;
	}
	
	@Bean
	public MessageSource messageSource() {
		MessageSource messageSource = new ResourceBundleMessageSource() {

			@Override
			public void setBasename(String basename) {
				super.setBasename("messages");
			}
			
		};
		return messageSource;
	}

	@Override
	public void configureHandlerExceptionResolvers(
			List<HandlerExceptionResolver> exceptionResolvers) {
		SimpleMappingExceptionResolver simpleExceptionResolver = new SimpleMappingExceptionResolver();

		Properties mappings = new Properties();
		mappings.setProperty("org.springframework.web.servlet.PageNotFound",
				"pageNotFound");
		mappings.setProperty("org.springframework.dao.DataAccessException",
				"dataAccessFailure");
		mappings.setProperty(
				"org.springframework.transaction.TransactionException",
				"dataAccessFailure");
		simpleExceptionResolver.setExceptionMappings(mappings);

		exceptionResolvers.add(simpleExceptionResolver);

		super.configureHandlerExceptionResolvers(exceptionResolvers);
	}
}
